#include "JFile.h"
#include "JSerialize.h"
#include <fstream>
#include "JLogger.h"
#include <boost/filesystem.hpp>
#include "JFileException.h"

using namespace boost::filesystem;

void JFile::CreateFile( std::string fileName )
{
	std::fstream fs(fileName.c_str(),std::fstream::out | std::fstream::trunc | std::fstream::binary);
	if(!fs)
	{
		throw JFileException("Function:JFile::CreateFile error.");
	}
	else
	{
		fs.close();
	}
}

JFile::JFile( std::string _fileName ):JBaseFile(_fileName)
{

}

std::fstream& JFile::OpenStream(std::ios_base::openmode _Mode)
{
	fs.open(this->filename.c_str(),_Mode);
	if(fs)
	{
            return fs;
	}
	else
	{
		throw JFileException("Function::OpenStream error.");
	}
}

void JFile::CloseStream()
{
	if(fs)
	{
            fs.close();
	}
}

bool JFile::IsExist( std::string fullFileName )
{
	path p(fullFileName);
	if(exists(p))
	{
		return true;
	}
	return false;
}

JFile::~JFile( void )
{

}

int JFile::Serialize( std::iostream& _strea,int& allSize )
{
	////Serialize begin.
	//std::fstream strea;
	////Serialize end.
	int classSize = 0,selfSize = 0;
	JSerialize::PutInt(_strea,classSize,selfSize);
	JBaseFile::Serialize(_strea,classSize);
	JSerialize::Serialize(_strea,this->OpenStream(std::ios::in | std::ios::binary),classSize);
	selfSize += classSize;
	JSerialize::Verify(_strea,classSize,-1*selfSize);
	this->CloseStream();
	allSize += selfSize;
	return selfSize;
}

void JFile::ReSerialize( std::iostream& _strea )
{
	this->OpenStream(std::ios::out | std::ios::binary | std::ios::trunc);
	int classSize = JSerialize::GetInt(_strea,sizeof(int));
	JBaseFile::Reserialize(_strea);
	JSerialize::ReSerializeFstream(_strea,this->fs);
	this->CloseStream();
}

int JFile::FileSize( std::string _fullFileName )
{
	return file_size(_fullFileName);
}

JFile::JFile()
{
    
}

void JFile::SaveToFileName(std::iostream& _strea,std::string _fullFileName)
{
    JFile file(_fullFileName);
    file.OpenStream(std::ios::out | std::ios::binary | std::ios::trunc);
    JSerialize::ReSerializeFstream(_strea,file.fs);
    file.CloseStream();
}